#include "http-database-client.h"
#include "http-database-client-store.h"

QMap<HttpDatabaseClientStore::DatabaseClientData,QWeakPointer<HttpDatabaseClient>> HttpDatabaseClientStore::m_databaseClients;
QMap<QObject*,HttpDatabaseClientStore::DatabaseClientData> HttpDatabaseClientStore::m_databaseClientObjects;

QSharedPointer<HttpDatabaseClient> HttpDatabaseClientStore::databaseClient (QString hostName, quint16 port)
{
    DatabaseClientData clientData(hostName, port);
    if (m_databaseClients.contains(clientData))
    {
        return m_databaseClients.value(clientData);
    }
    else
    {
        QSharedPointer<HttpDatabaseClient> databaseClient(new HttpDatabaseClient());
        databaseClient->setHostName(hostName);
        databaseClient->setPort(port);
        connect (databaseClient.data(), &HttpDatabaseClient::destroyed, &HttpDatabaseClientStore::removeDatabaseClient);

        m_databaseClientObjects.insert(databaseClient.data(), clientData);
        m_databaseClients.insert(clientData, databaseClient.toWeakRef());
        return databaseClient;
    }
}

void HttpDatabaseClientStore::removeDatabaseClient (QObject *databaseClientObject)
{
    m_databaseClients.remove(m_databaseClientObjects.value(databaseClientObject));
    m_databaseClientObjects.remove(databaseClientObject);
}

HttpDatabaseClientStore::DatabaseClientData::DatabaseClientData()
    : m_port(0)
{
}

HttpDatabaseClientStore::DatabaseClientData::DatabaseClientData (QString hostName, quint16 port)
    : m_hostName(hostName), m_port(port)
{
}

bool HttpDatabaseClientStore::DatabaseClientData::operator< (const HttpDatabaseClientStore::DatabaseClientData &other) const
{
    int comparison = QString::compare(m_hostName, other.m_hostName);
    if (comparison == 0)
        return m_port < other.m_port;
    else
        return comparison < 0;
}
